import { history, RequestConfig } from 'umi';
import {notification} from 'antd';
import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';

import defaultSettings from '../config/defaultSettings';

import { getCookie, removeCookie } from '@/utils/cookie';
import { merge, cloneDeep } from 'lodash';

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
    loading: <PageLoading />,
};

export async function getInitialState(): Promise<{
    settings?: Partial<LayoutSettings>;
    currentUser?: AircasKB.User;
    loading?: boolean;
    knowledgeId?:string;
    fetchUserInfo?: () => Promise<AircasKB.User | undefined>;
}> {
    const fetchUserInfo = async () => {
        let _user = getCookie('Aircas-User');
        if (_user) {
            return JSON.parse(_user) as AircasKB.User;
        }
        return undefined;
    };
    // 如果不是登录页面，执行
    if (history.location.pathname !== loginPath) {
        const currentUser = await fetchUserInfo();
        return {
            fetchUserInfo,
            currentUser,
            settings: defaultSettings,
        };
    }
    return {
        fetchUserInfo,
        settings: defaultSettings,
    };
}

const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '操作失败。',
    400: '客户端请求的语法错误。',
    401: '权限错误，您无权操作此功能。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    410: '请求的资源被永久删除，且不会再得到的。',
    500: '服务器发生错误，请联系管理员告知该情况。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
    1000: '未登录',
    1001: '用户名或密码错误',
};

// const { cancel } = Reqs.CancelToken.source();
interface error {
    name:string,
    data:any,
    type: string,
    response:{
        status:number,
        statusText:string,
        url:string
    }
}

// @ts-ignore
export const request: RequestConfig = {
    // prefix: config.post_url,
    // @ts-ignore
    prefix:window.config.post_url, //process.env.NODE_ENV === 'production' ? window.config.post_url : process.env.HOST_URL,
    // @ts-ignore
    timeout: window.config.timeout,
    // credentials: 'omit',
    errorConfig: {
        adaptor: res => {
            return {
                success: res.success,
                data:res.data,
                errorCode:res.code,
                errorMessage: res.message,
            };
        },
    },
    errorHandler: (error:error) => {
        if(error.name==="BizError"){
            if(error.data.code === 1000){
                notification.warn({
                    message: codeMessage[error.data.code]+',请重新登录!',
                });
                removeCookie('Aircas-User');
                removeCookie('Aircas-TOKEN');
                history.push(loginPath);
            }else{
                notification.error({
                    message: `错误提示`,// ${error.data.code}
                    description: error.data.message,
                });
            }
            return error.data.code;
        }
        const { response } = error;
        if(response){
            const errortext = codeMessage[response.status || 202] || response.statusText;
            const { status, url } = response;
            let noParamUrl = url;
            if (url.indexOf('?') !== -1) {
                noParamUrl = url.substring(0, url.indexOf('?'));
            }
            notification.error({
                message: `请求错误 ${status}: ${noParamUrl}`,
                description: errortext,
            });
            return response;
        }
        else{
            notification.error({
                message: `超时提醒:`,
                description: '接口访问超时！',
            });
            return error;
        }
    },

    requestInterceptors: [
        (url, options) => {
            const _token = getCookie('Aircas-TOKEN');
            if(url.indexOf('mockApi')>-1){
                const res:string[] = url.split('/');
                return {
                    // @ts-ignore
                    url:window.config.mock_url+`/mockApi/`+res[res.length-1],
                    options: merge(cloneDeep(options), {
                        'Content-Type': 'application/json',
                        headers: { Authorization: _token },
                    }),
                };
            }
            else{
                return {
                    url,
                    options: merge(cloneDeep(options), {
                        'Content-Type': 'application/json',
                        headers: { Authorization: _token },
                    }),
                };
            }

        },
    ],
    // responseInterceptors:[
    //     async (response)=>{
    //         const data = await response.clone().json();
    //         if(data && data.code && data.code != 200){
    //             notification.error({
    //                 message: `错误提示`,
    //                 description: data.message ,
    //             });
    //             if (data.code == 1000) {
    //                 // history.push('/user/login');
    //             }
    //         }
    //         return response;
    //     }
    // ],
};
